package mapper

import (
	"cooke-home/common/handle"
	"cooke-home/common/model/base_dto"
	"cooke-home/task-service/model/dto"
	"cooke-home/task-service/model/entity"

	"gorm.io/gorm"
)

type TaskMapperImpl struct {
	DB        *gorm.DB
	TableName string
}

func NewTaskMapperImpl() *TaskMapperImpl {
	return &TaskMapperImpl{
		DB:        handle.DB,
		TableName: "t_task",
	}
}

func (tm *TaskMapperImpl) Save(taskDto *dto.TaskDto) error {
	return tm.DB.Table(tm.TableName).Create(taskDto).Error
}

func (tm *TaskMapperImpl) Delete(batchDeleteDto base_dto.BatchDeleteDto) error {
	return tm.DB.Table(tm.TableName).Where("task_id IN ?", batchDeleteDto.IDs).Delete(&dto.TaskDto{}).Error
}

func (tm *TaskMapperImpl) Update(taskDto *dto.TaskDto) error {
	return tm.DB.Table(tm.TableName).Where("task_id = ?", taskDto.TaskID).Updates(taskDto.TaskEntity).Error
}

func (tm *TaskMapperImpl) Get(id int64) (*entity.TaskEntity, error) {
	var model entity.TaskEntity
	err := tm.DB.Table(tm.TableName).Where("task_id = ?", id).First(&model).Error
	if err != nil {
		return nil, err
	}
	return &model, nil
}

func (tm *TaskMapperImpl) GetList(parentId int64) ([]*entity.TaskEntity, error) {
	var models []*entity.TaskEntity
	err := tm.DB.Table(tm.TableName).Where("parent_id = ?", parentId).Find(&models).Error
	if err != nil {
		return nil, err
	}
	return models, nil
}

func (tm *TaskMapperImpl) UpdateCompleteByParentId(taskDto *dto.TaskDto) error {
	return tm.DB.Table(tm.TableName).
		Where("parent_id = ? or task_id = ?", taskDto.ParentID, taskDto.ParentID).
		Update("is_complete", taskDto.IsComplete).Error
}

func (tm *TaskMapperImpl) GetByComplete(parentId int64, isComplete int) ([]*entity.TaskEntity, error) {
	var models []*entity.TaskEntity
	err := tm.DB.Table(tm.TableName).
		Where("parent_id = ? and is_complete = ?", parentId, isComplete).Find(&models).Error
	if err != nil {
		return nil, err
	}
	return models, nil
}
